import { Component, EventEmitter, Injector, Input, OnInit, Output, OnChanges, SimpleChanges, ViewChild, TemplateRef, ElementRef } from '@angular/core';
import { AppComponentBase } from '@shared/component-base';
import { TokenService } from 'abp-ng2-module/dist/src/auth/token.service';
import { AppConsts } from 'abpPro/AppConsts';
import { UploadChangeParam, UploadFile } from 'ng-zorro-antd';
import { CustomFormGroup, CustomFormItem, CustomFormListItem, itemType, Precondition } from '../../custom-form.type';

@Component({
    selector: 'app-custom-form-editor-item',
    styleUrls: ['./custom-form-editor-item.component.less'],
    templateUrl: './custom-form-editor-item.component.html',
    styles: []
})
export class CustomFormEditorItemComponent extends AppComponentBase implements OnInit, OnChanges {

    constructor(injector: Injector) {
        super(injector);
    }
    @Input() isReadOnly = true;

    @Input() isPreview = false;

    @Input() formJson: CustomFormGroup = new CustomFormGroup();

    @Input() item: CustomFormItem;

    @Input() itemJson: string;

    @Input() isEditor = true;

    @Input() groupIndex = '';

    @Output() getItemChange: EventEmitter<CustomFormItem> = new EventEmitter<CustomFormItem>();

    @Input() listItem: CustomFormListItem;
    // @Output() preconditionChange: EventEmitter<Precondition[]> = new EventEmitter<Precondition[]>();

    fileUploadUrl: string = AppConsts.remoteServiceBaseUrl + "/api/services/app/Attachment/UploadFile";

    fileUploadHeader: {
        Authorization: string
    };
    isShowTypeModal = false;
    selectPrecondition: Precondition;
    getItem = (item: CustomFormItem) => {
        this.getItemChange.emit(item);
    }
    ngOnInit() {
        this.fileUploadHeader = { Authorization: "Bearer " + new TokenService().getToken() };
    }
    ngOnChanges(changes: SimpleChanges) {
        if (this.hasChange('itemJson', changes)) {
            setTimeout(() => {
                this.item = changes['itemJson'].currentValue ? CustomFormItem.fromJson(JSON.parse(changes['itemJson'].currentValue)) : undefined;
            }, 0);
        }
    }
    hasChange(key: string, changes: SimpleChanges): boolean {
        return changes && key in changes && !changes.firstChange &&
            changes[key].currentValue !== changes[key].previousValue;
    }
    onCheckBoxChange(item: CustomFormItem) {
        setTimeout(() => {
            if (item.maxSelected <= item.options.filter(v => v.checked).length) {
                item.options.forEach(v => v.disable = !v.checked);
            } else {
                item.options.forEach(v => v.disable = false);
            }
        }, 0);
    }
    fileUploadBefor = () => {
        if (this.isEditor || this.isReadOnly || this.isPreview) return false;
        else return true;
    }
    fileUploadChange(fc: UploadChangeParam, item: CustomFormItem) {
        switch (fc.file.status) {
            case "done": // 上传完成
                // 获取服务端返回的信息
                if (fc.file.response.success) {
                    item.files.push(fc.file.response.result);
                }
                break;
            case "error": // 上传错误
                abp.message.error(this.l("UploadFailed"));
                break;
        }
    }
    fileRemove(item: CustomFormItem) {
        return (file: UploadFile) => {
            const idx = item.files.findIndex(f => f.id === file.uid);
            if (idx !== -1) item.files.splice(idx, 1);
            return true;
        };
    }
    addProItem(opt: { key: string }) {
        console.log(opt);
        if (!this.listItem.precondition) this.listItem.precondition = [];
        this.selectPrecondition = this.listItem.precondition.find(f => f.OptionKey.key === opt.key);
        if (!this.selectPrecondition) {
            this.selectPrecondition = new Precondition(this.item, opt.key);
            this.listItem.precondition.push(this.selectPrecondition);
        }
        this.selectPrecondition.type = 'selected';
        if (!this.selectPrecondition.children) this.selectPrecondition.children = [];
        this.isShowTypeModal = true;
    }
    addItem(type: itemType) {
        this.selectPrecondition.children.push(new CustomFormListItem(new CustomFormItem(type)));
        this.isShowTypeModal = false;
        this.formJson.reSetKey();
        console.log(this.listItem.precondition, this.selectPrecondition);
    }
    addGroup() {
        this.selectPrecondition.children.push(new CustomFormListItem(new CustomFormGroup()));
        this.isShowTypeModal = false;
        this.formJson.reSetKey();
    }
}
